package com.dx.mes.service.spc.service;


import com.dx.common.table.ppt.Spc_bis_chart_main;
import com.dx.common.table.ppt.Spc_bis_chart_mainId;
import com.dx.mes.common.dao.ISpcBisChartMainDao;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LogUtil;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.service.pojo.Spc_bis_chart_setting;
import com.dx.mes.service.spc.tx.ChartMain.ChartMainInPo;
import com.dx.mes.service.spc.tx.ChartMain.ChartMainOutPo;
import org.hibernate.*;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

import static com.dx.mes.common.bean.def.GenericDef.*;

/**
 * @Title: SPCChartMainService.java
 * @Package com.serviceimpl
 * @Description: SPC chart图相关处理Service
 * @author Lynn.Sea
 * @date 2014-2-17 下午7:52:01
 * @version V1.0
 */
@Service("spcChartMainServiceImpl")
public class ChartServiceImpl implements IChartService {
	private static final String TRX_NAME_SPC_CHART_MAIN_TRX = "XPCCHTMN";
	private LogUtils logUtils;
	
	@Autowired
    SessionFactory sessionFactory;
	@Autowired
	private ISpcBisChartMainDao spcBisChartMainDao;
	
	public String subMainProc(String evt_no,String strInMsg) {
		AppContext.clear();
		AppContext.setCurrServiceName(ChartServiceImpl.class.getSimpleName());
		AppContext.setCurrEventNumber(evt_no);
		logUtils = new LogUtils(ChartServiceImpl.class);
		logUtils.info("[InTrx:" + strInMsg + "]");
		
		String strOutMsg = "";
		Session session = spcBisChartMainDao.getCrSession();
		ChartMainInPo inTrx = new ChartMainInPo();
		ChartMainOutPo outTrx = new ChartMainOutPo();
		outTrx.setTrx_id(TRX_NAME_SPC_CHART_MAIN_TRX);
		outTrx.setType_id("O");
		try {
			inTrx = JacksonUtil.fromJson(strInMsg, ChartMainInPo.class);
			char action_flg = inTrx.getAction_flg().charAt(0);
			switch( action_flg ){
				case 'Q' : querySPCChartSetting(inTrx, outTrx); break;
				default  : errActionFnc(inTrx, outTrx);   
			}
			if( RETURN_CODE_OK.equals(outTrx.getRtn_code()) ){
				session.flush();
				outTrx.setRtn_code(RETURN_CODE_OK);
				outTrx.setRtn_mesg(RETURN_MESG_OK);
			}else{
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		} catch (Exception ex) {
			outTrx.setRtn_code("0000001");
			outTrx.setRtn_msg(ex.getMessage());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} finally {
			strOutMsg = JacksonUtil.toJSONStr(outTrx);
			logUtils.info("[OutTrx:" + strOutMsg + "]");
		}
		return strOutMsg;

	}


	public void querySPCChartSetting(ChartMainInPo inTrx, ChartMainOutPo outTrx) {
		try {
			List<Spc_bis_chart_setting> spcBisChartSettingList = querySPCChartSetting(inTrx.getCol_typ(),
					inTrx.getGrp_no(), inTrx.getChart_no(), inTrx.getChart_typ());
			outTrx.setOaryB(spcBisChartSettingList);
			outTrx.setTbl_cnt(spcBisChartSettingList.size());
			outTrx.setRtn_code(RETURN_CODE_OK);
			outTrx.setRtn_mesg(RETURN_MESG_OK);
		} catch (Exception e) {
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg(LogUtil.stackTraceToString(e));
			e.printStackTrace();
			return;
		}
	}
	public List<Spc_bis_chart_main> queryAllSpcChartMain() {
		Session session = sessionFactory.getCurrentSession();
		return session.createQuery("FROM Spc_bis_chart_main").list();
	}

	public List<Spc_bis_chart_main> querySpcChartMain(ChartMainInPo inTrx) {
		Session session = sessionFactory.getCurrentSession();
		Spc_bis_chart_main spc_bis_chart_main = new Spc_bis_chart_main();
		Spc_bis_chart_mainId spc_bis_chart_mainId = new Spc_bis_chart_mainId();
		spc_bis_chart_mainId.setCol_typ_fk(inTrx.getCol_typ());
		spc_bis_chart_mainId.setGrp_no_fk(inTrx.getGrp_no());
		spc_bis_chart_main.setId(spc_bis_chart_mainId);
		Criteria criteria = session.createCriteria(Spc_bis_chart_main.class);
		if(inTrx.getCol_typ()!=null){
			criteria.add(Restrictions.eq("col_typ_fk", inTrx.getCol_typ()));
		}
		if(inTrx.getGrp_no()!=null){
			criteria.add(Restrictions.eq("grp_no_fk", inTrx.getGrp_no()));
		}
		if(inTrx.getData_group()!=null){
			criteria.add(Restrictions.eq("data_group_fk", inTrx.getData_group()));
		}
		if(inTrx.getChart_name()!=null){
			criteria.add(Restrictions.like("chart_name", inTrx.getChart_name()));
		}
		if(inTrx.getChart_dsc()!=null){
			criteria.add(Restrictions.like("chart_dsc", inTrx.getChart_dsc()));
		}
		if(inTrx.getChart_owner()!=null){
			criteria.add(Restrictions.like("chart_owner", inTrx.getChart_owner()));
		}
		criteria.addOrder(Order.asc("col_typ_fk"));
		criteria.addOrder(Order.asc("grp_no_fk"));
		criteria.addOrder(Order.asc("chart_name"));
		return criteria.list();
		
	}

	public Spc_bis_chart_main querySPCChartMainByKey(String col_typ,
                                                     String grp_no, String chart_no) {
		Session session = sessionFactory.getCurrentSession();
		Query query = session
				.createQuery("FROM Spc_bis_chart_main where col_typ_fk=:col_typ_fk and grp_no_fk=:grp_no_fk and chart_no=:chart_no");
		query.setString("col_typ_fk", col_typ);
		query.setString("grp_no_fk", grp_no);
		query.setString("chart_no", chart_no);
		return (Spc_bis_chart_main)query.uniqueResult();
	}
	public List<Spc_bis_chart_setting> querySPCChartSetting(String col_typ,
                                                            String grp_no, String chart_no, String chart_typ) {
		
		Session session = sessionFactory.getCurrentSession();
		StringBuffer buffer = new StringBuffer();
		
		buffer.append("SELECT ").append("col_typ,grp_no,chart_no,chart_typ_fk AS chart_typ,")
				.append("grp_name,grp_dsc,")
				.append("chart_name,CH_MAIN.DATA_GROUP_FK as data_group,chart_dsc,chart_owner,")
				.append("max_chart_point, sample_size,")
				.append("chart_upl,chart_ual,chart_usl,chart_ucl,chart_uwl,")
				.append("chart_lpl,chart_lal,chart_lsl,chart_lcl,chart_lwl,")
				.append("chart_target,chart_mean ");
		buffer.append("FROM").append(" SPC_BIS_GRP_MAIN  GR_MAIN  ,")
				.append("SPC_BIS_CHART_MAIN CH_MAIN ,")
				.append("SPC_RET_CHART_INFO CH_INFO  ");
		buffer.append("WHERE ")
				.append("GR_MAIN.COL_TYP = CH_MAIN.COL_TYP_FK AND GR_MAIN.COL_TYP = CH_INFO.COL_TYP_FK ")
				.append("AND GR_MAIN.COL_TYP = CH_INFO.COL_TYP_FK ")
				.append("AND GR_MAIN.GRP_NO = CH_MAIN.GRP_NO_FK AND GR_MAIN.GRP_NO = CH_INFO.GRP_NO_FK ")
				.append("AND GR_MAIN.GRP_NO = CH_INFO.GRP_NO_FK ")
				.append("AND CH_MAIN.CHART_NO = CH_INFO.CHART_NO_FK ");
		buffer.append("AND col_typ=:col_typ AND grp_no=:grp_no ")
				.append("AND chart_no=:chart_no ");
		
		if (chart_typ != null) {
			buffer.append("AND chart_typ=:chart_typ");
		}
		
		SQLQuery query = session.createSQLQuery(buffer.toString());
		query.setString("col_typ", col_typ);
		query.setString("grp_no", grp_no);
		query.setString("chart_no", chart_no);
		
		if (chart_typ != null){
			query.setString("chart_typ", chart_typ);
		}
		
//		query.addScalar("col_typ", Hibernate.STRING);
//		query.addScalar("grp_no", Hibernate.STRING);
//		query.addScalar("chart_no", Hibernate.STRING);
//		query.addScalar("chart_typ", Hibernate.STRING);
//		query.addScalar("grp_name", Hibernate.STRING);
//		query.addScalar("grp_dsc", Hibernate.STRING);
//		query.addScalar("chart_name", Hibernate.STRING);
//		query.addScalar("data_group", Hibernate.STRING);
//		query.addScalar("chart_dsc", Hibernate.STRING);
//		query.addScalar("chart_owner", Hibernate.STRING);
//		query.addScalar("max_chart_point", Hibernate.INTEGER);
//		query.addScalar("sample_size", Hibernate.INTEGER);
//		query.addScalar("chart_upl", Hibernate.DOUBLE);
//		query.addScalar("chart_ual", Hibernate.DOUBLE);
//		query.addScalar("chart_usl", Hibernate.DOUBLE);
//		query.addScalar("chart_ucl", Hibernate.DOUBLE);
//		query.addScalar("chart_target", Hibernate.DOUBLE);
//		query.addScalar("chart_mean", Hibernate.DOUBLE);
//		query.addScalar("chart_uwl", Hibernate.DOUBLE);
//		query.addScalar("chart_lpl", Hibernate.DOUBLE);
//		query.addScalar("chart_lal", Hibernate.DOUBLE);
//		query.addScalar("chart_lsl", Hibernate.DOUBLE);
//		query.addScalar("chart_lcl", Hibernate.DOUBLE);
//		query.addScalar("chart_lwl", Hibernate.DOUBLE);
//		query.setResultTransformer(Transformers.aliasToBean(Spc_bis_chart_setting.class));
		return query.list();
	}
	
	public void errActionFnc(ChartMainInPo inTrx, ChartMainOutPo outTrx){
		outTrx.setRtn_code("0000009");
		outTrx.setRtn_mesg("Invalid Action_flg");
	}
}
